<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Grade;
use app\common\model\Subject;
use app\common\model\TeacherJob as TeacherJobModel;
use app\common\model\StaffOrder as StaffOrderModel;
use app\common\validate\TeacherJob as TeacherJobValidate;
use think\Config as ThinkConfig;
use think\Db;

class TeacherJob extends Api
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    //帮您选师
    public function apply()
    {
        $audit_on = ThinkConfig::get('site.audit_on',0);
        if($audit_on==1){
            $this->success('提交成功');
        }
        $param = $this->request->param();

        $param['user_id'] = $this->auth->id;

        $validate = new TeacherJobValidate();

        if (!$validate->scene('add')->check($param)) {
            $this->error($validate->getError());
        }

        $finding = (new TeacherJobModel())->where([
            'user_id' => $this->auth->id,
            'status' => ['in','1,2,3']
        ])->find();
        if($finding){
            $this->error('请先完结之前的急招订单，再进行操作！');
        }


        $param['subject'] = (new Subject)->where([
            'id' => $param['subject']
        ])->value('name');

        $param['grade'] = (new Grade())->where([
            'id' => $param['grade']
        ])->value('name');

        $param['addr'] = implode(',',$param['addr']);

        $parents_pay_deposit = ThinkConfig::get('site.parents_pay_deposit');

        $close_time = 15; //15分钟为支付自动关闭

        $order = [];
        $order['order_sn'] = $param['order_sn'] = xykeepCreateOrderNo();
        $order['total_amount'] = $param['total_amount'] = $parents_pay_deposit;
        $order['total_fee'] = $param['total_fee'] = $parents_pay_deposit;
        $order['ext'] = $param['ext'] = json_encode([
            'expired_time' => time() + ($close_time * 60),
        ]);

        $res = (new TeacherJobModel())->save($param);
        $order['id'] = (new TeacherJobModel())->getLastInsID();
        if($res){
            $this->success('申请成功',['money'=>$parents_pay_deposit,'order'=>$order]);
        }else{
            $this->error('申请失败');
        }
    }

    //急招详情
    public function detail()
    {
        $params = $this->request->post();
        $TeacherJobModel = new TeacherJobModel();

        if(!isset($params['id']) || empty($params['id'])){
            $this->error('参数错误');
        }
        $detail = $TeacherJobModel->where([
            'id' => $params['id']
        ])->find();
        if(!$detail){
            $this->error('数据错误');
        }

        if($this->auth->isLogin()){
            $detail['applyed'] = (new StaffOrderModel())->where([
                'user_id' => $this->auth->id,
                'status' => ['in','1,2'],
                'job_id' => $detail['id']
            ])->find();
        }

        $this->success('急招详情',$detail);
    }

    //快速接单列表
    public function lists()
    {
        $params = $this->request->post();

        $order = 'id desc';
        $field = '*';
        if($params['lat'] && $params['lng']){
            $order = 'distance asc';
            $field .= ",ROUND( ST_Distance_Sphere( POINT(" . $params['lng'] . ", " . $params['lat'] . "), POINT(lng, lat) ) / 1000, 1) AS distance";
        }

        $already_ids = (new StaffOrderModel())->where([
            'user_id' => $this->auth->id,
            'status' => ['in','1,2,3']
        ])->column('job_id');

        $lists = (new TeacherJobModel())->field($field)->where([
            'status' => 2,
            'id' => ['not in',$already_ids]
        ])->order($order)->paginate(10);

//        $lists->each(function($item, $key){
//           $item['test'] = 1;
//        });


        $this->success('',$lists);

    }

    //查看家长最近一次的急招
    public function only()
    {
        $params = $this->request->post();
        if(isset($params['id']) && $params['id']){
            $data = (new TeacherJobModel())->field('*')->where([
                'user_id' => $this->auth->id,
                'id' => $params['id'],
            ])->find();
        }else{
            //默认取正在急招的那条，有且只能有一条
            $data = (new TeacherJobModel())->field('*')->where([
                'user_id' => $this->auth->id,
                'status' => ['in','2,3']
            ])->find();
        }
        if(empty($data)){
            $this->error('没有正在急招的订单');
        }

        $data['title'] = $data['demand'];

        $staff_list = (new StaffOrderModel())->with('user')->where([
            'job_id' => $data['id'],
            'status' => ['neq',0]
        ])->select();
        foreach($staff_list as $k=>&$v){
            $teacher = Db::name('teacher')->where([
                'user_id' => $v['user_id']
            ])->find();
            $v['lat'] = $teacher['unholiday_area_lat'];
            $v['lng'] = $teacher['unholiday_area_lng'];
            $v['title'] = $teacher['nickname'];
        }
        $data['staff_list'] = $staff_list;
        $this->success('',$data);
    }

    //完结订单：老师接单了，老师上门试完课，老师和家长当场双方都点击完成试课以后，家长的押金即时直接自动退回；
    public function overOrder()
    {
        $params = $this->request->post();

        try{
            Db::startTrans();
            $detail = (new TeacherJobModel())->where([
                'user_id' => $this->auth->id,
                'id' => $params['id'],
                'status' => 3
            ])->find();

            if(!$detail){
                throw new \Exception('数据错误');
            }

            $unPickStaff = (new StaffOrderModel())->where([
                'job_id' => $params['id'],
                'status' => 2
            ])->find();

            if($unPickStaff){
                //家教没点击过“完成”，订单标记一下
//                throw new \Exception('请先确保兼职人员的接单状态已完结，再进行操作，若兼职人员无法点击完结，请点击客服介入');
                $detail->agreetime = time();
                $detail->save();
            }else{
                //家教已经点击完成了，订单终结
                $detail->status = 4;
                $detail->refundtime = time();
                $detail->agreetime = time();
                $detail->save();

                //家长退款
                $params['order'] = $detail;
                $params['type'] = 'job';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }

            //家教退款
//            $staffOrder = (new StaffOrderModel())->where([
//                'job_id' => $params['id'],
//                'status' => 3
//            ])->find();
//            $staffOrder->refundtime = time();
//            $staffOrder->save();
//            $params['order'] = $staffOrder;
//            $params['type'] = 'staff';
//            \think\Hook::listen('xykeep_order_refund_after', $params);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功',$unPickStaff?3:4);
    }

    //申请平台介入
    public function platformIntervention()
    {
        $params = $this->request->post();

        $detail = (new TeacherJobModel())->where([
            'user_id' => $this->auth->id,
            'id' => $params['order_id'],
            'status' => ['in','3']
        ])->find();

        if(!$detail){
            $this->error('数据错误');
        }

        $detail->normal = 0;
        $detail->save();

        $message = array(
            'character_string2' => '2',
            'thing1' => '家教平台',
        );
        $res = \addons\weixin\library\WechatTemplateService::sendFastTemplate(
            'oNhI9vuKmri8OvHLHOd-rxasCn2k',//用户openid
            'rgae_FaeGj69Aqu-AEWGEYc_zzYYWaQlZH3Gv3qH6cU',//自定义模板编号
            $message,
            ''
        );

        $this->success('操作成功');
    }

    //取消急招订单
    public function cancelOrder()
    {
        $params = $this->request->post();

        try{
            Db::startTrans();

            $detail = (new TeacherJobModel())->where([
                'user_id' => $this->auth->id,
                'id' => $params['id'],
            ])->find();

            if(!$detail){
                throw new \Exception('数据错误');
            }


            if($detail['status']==3){
                //有老师报名了，并锁定了，这种时候家长的押金不退

                $detail->status = -2;
                $detail->save();

//                throw new \Exception('已有锁定兼职人员，无法取消订单');
            }else{
                //没有锁定
                $detail->status = -2;
                $detail->refundtime = time();
                $detail->save();

                $params['order'] = $detail;
                $params['type'] = 'job';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }

            $already_lock = (new StaffOrderModel())->where([
                'job_id' => $params['id'],
                'status' => 2
            ])->find();

            if($already_lock){
                $already_lock->refundtime = time();
                $already_lock->status = -1;
                $already_lock->save();

                $params['order'] = $already_lock;
                $params['type'] = 'staff';
                \think\Hook::listen('xykeep_order_refund_after', $params);
            }

            \think\Hook::listen('xykeep_job_refund_all', $params['id']);



            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('操作成功');
    }
}